

#include "error.h"

#include <kernel/handle/handle.h>

static int ErrorNumber = ERROR_OK;

static const char *ErrorTable [] = {
	"",
	"I've got nothing",
	"I'm out of memory blocks",
	"I'm out of handles",
	"I'm out of userids",
	"The resource you requested was locked",
	"You were denied permission to access a resource",
	"I don't have any more room",
	"I reached the end unexpectedly"
};

static handle ErrorLog;
static userid ID;

extern void error_init ()
{
	ID = userid_request ();
	ErrorLog = handle_request ("kernel.error", ID);
}

extern int error_get ()
{
	return ErrorNumber;
}


extern void error_set (int _err)
{
	ErrorNumber = _err;
}


extern const char *error_tostring (int _err)
{
	return ErrorTable [_err];
}


extern int error_log (int _err)
{
	error_set (_err);

	if (handle_trylock (ErrorLog) != 0)
	{
		error_set (ERROR_LOCKED);

		return -1;
	}

	handle_writestring (ErrorLog, "kernel error: ");
	handle_writestring (ErrorLog, error_tostring (_err));
	handle_writestring (ErrorLog, ".\n");

	handle_unlock (ErrorLog);

	return 0;
}


extern userid error_userid ()
{
	return ID;
}
